package com.anxinr.config;

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 请求参数增强器
 * @author : anxinr
 * @date : 2022/10/11 14:30
 */
public class RequestBodyWrapper extends HttpServletRequestWrapper {
    /**
     * 定义字节数组, 缓存请体信息
     */
    private final byte[] requestBody;

    /**
     * 重写构造器
     * @param request
     * @throws IOException
     */
    public RequestBodyWrapper(HttpServletRequest request) throws IOException {
        super(request);
        requestBody = StreamUtils.copyToByteArray(request.getInputStream());
    }

    /**
     * desc 重写获取request请求的输入流方法, 从复制的字节数组中获取
     * date 2022/9/6 9:40
     * @author anxinr
     * @return {@link ServletInputStream}
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);

        return new ServletInputStream() {

            @Override
            public int read(){
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}
